package com.lzc.customer.dao;
import com.lzc.DBUtil;
import com.lzc.customer.model.Customer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomerDao {
    /*根据会员名称来查询会员信息*/
    public Customer getCustomerByName(String username) {
        Connection conn = DBUtil.getConnection();
        String sql = "select * from tb_customer where user_name=?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if(rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt("id"));
                customer.setEmail(rs.getString("email"));
                customer.setMobile(rs.getString("mobile"));
                customer.setPassword(rs.getString("password"));
                customer.setReal_name(rs.getString("real_name"));
                customer.setUser_name(rs.getString("user_name"));
                return customer;
            }
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.closeResource(conn,ps,rs);
        }
        return null;
    }
    /**根据用户名及密码添加会员信息 */
    public int addCustomer(String username,String password){
        //判断账号是否存在
        Customer customer=getCustomerByName(username);
        if(customer == null){
            Connection conn = DBUtil.getConnection();
            String sql="INSERT INTO `tb_customer`(`user_name`,`password`) VALUES(?,?)";
            PreparedStatement ps = null;
            try {
                ps = conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                //执行并更新数据库，返回数据库中受影响的行数
                int num = ps.executeUpdate();
                return num;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                DBUtil.closeResource(conn,ps,null);
            }
        }else{
            //账号已存在，返回0表示失败
            return 0;
        }
    }
}